package com.sinoglobal.sinostore.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.sinoglobal.sinostore.R;
import com.sinoglobal.sinostore.ShareAbstractActivity;
import com.sinoglobal.sinostore.adapter.GoodsFragmentAdapter;
import com.sinoglobal.sinostore.bean.BaseVo;
import com.sinoglobal.sinostore.bean.BuyNowVo;
import com.sinoglobal.sinostore.bean.GoodsDetailsVo;
import com.sinoglobal.sinostore.dialog.ShopDialogStyle3;
import com.sinoglobal.sinostore.fragment.GoodsDetailFragment.OrderDataInterface;
import com.sinoglobal.sinostore.fragment.GoodsWebFragment;
import com.sinoglobal.sinostore.listener.OnAntiViolenceClickListener;
import com.sinoglobal.sinostore.system.Constants;
import com.sinoglobal.sinostore.utils.SignUtil;
import com.sinoglobal.sinostore.widget.view.TryViewPager;

/**
 * @author zrh
 * @title: GoodsDetailActivity.java
 * @package com.chiliring.sinostore.activity
 * @description: 商品详情页面
 * @date 2015年1月15日 下午2:33:05
 */
public class GoodsDetailActivity extends ShareAbstractActivity implements OrderDataInterface {
    /**
     * 商家Id
     **/
    public static String shopId;
    /**
     * 商品id
     **/
    public static String goodsId;

    private TryViewPager pager;

    private View goodsWebFragment;

    private GoodsFragmentAdapter adapter;

    /**
     * 收藏
     **/
    private TextView btnCollection;

    /**
     * 立即购买
     **/
    private TextView btnShopping;

    /**
     * 商品详情
     **/
    private GoodsDetailsVo detailsVo;

    /**
     * 商品下架
     **/
    private View goodsDown;
    /**
     * 商品详情
     **/
    private RelativeLayout rlDetailsLayout;
    /**
     * 底部按钮
     **/
    private View detailButtom;
    /**
     * 去逛逛
     **/
    private Button btnGoToMall;

    GoodsWebFragment fragment;
    boolean isFragmentShow = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shop_goods_detail);
//        openChenJInShi();
        goodsId = null;
        shopId = null;
        titleView.setText("商品详情");
        pager = getViewById(R.id.pager);
        goodsWebFragment = getViewById(R.id.goodsWebFragment);
        btnCollection = getViewById(R.id.btn_collection);
        btnShopping = getViewById(R.id.btn_shopping);
        goodsDown = getViewById(R.id.goods_down);
        rlDetailsLayout = getViewById(R.id.rl_detail_layout);
        detailButtom = getViewById(R.id.goodsDetailBottom);
        btnGoToMall = getViewById(R.id.btn_GoToMall);

        templateButtonLeft.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        // 防止放在他下面的view响应touch事件
        goodsWebFragment.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.onTouchEvent(event);
                return true;
            }
        });
        fragment = new GoodsWebFragment();
        initView();
        initData();
        openChenJInShi();
    }

    private void initData() {
        Bundle bundle = getIntent().getExtras();
        Intent intent = new Intent();
        intent.putExtras(bundle);
        adapter = new GoodsFragmentAdapter(getSupportFragmentManager());
        pager.setAdapter(adapter);
    }

    private void initView() {
        btnCollection.setOnClickListener(clickListener);
        btnShopping.setOnClickListener(clickListener);
        titleRightText.setText("联系客服");
        baseButRight.setOnClickListener(clickListener);
        btnGoToMall.setOnClickListener(clickListener);
    }

    @Override
    public void onBackPressed() {
        // if (goodsWebFragment.getVisibility()==View.VISIBLE) {
        if (isFragmentShow) {
            dismissWebView();
        } else {
            super.onBackPressed();
        }
    }

    private void dismissWebView() {
        getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.slide_out_left, R.anim.slide_out_left).remove(fragment)
                .commit();
        isFragmentShow = false;
    }

    public void toGoodsWebView() {
        if (!isFragmentShow) {
            getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.slide_in_right, 0)
                    .add(R.id.shop_view_mainBody, fragment).addToBackStack(null).commit();
            isFragmentShow = true;
        }
    }

    /**
     * 按钮监听
     */
    private OnAntiViolenceClickListener clickListener = new OnAntiViolenceClickListener() {

        @Override
        public void onAVClick(View v) {
            int id = v.getId();
            if (id == R.id.btn_collection) {
                if (isLogin()) {
                    if (detailsVo.is_collected == 0) {
                        addCollection();// 添加收藏
                    } else {
                        concelConnection();// 取消收藏
                    }
                }
            } else if (id == R.id.btn_shopping) {
                // 如果在秒杀活动时间内
                if (isLogin()) {
                    if ("0".equals(detailsVo.nums)) {
                        showShortToast("已卖完");
                        return;
                    }
                    if (Constants.ISMS == detailsVo.is_ms) {
                        buyNow();
                    } else {
                        if ("0".equals(detailsVo.available) && !"0".equals(detailsVo.restriction)) {
                            int num = Integer.parseInt(detailsVo.restriction) - Integer.parseInt(detailsVo.available);
                            showShortToast(String.format("宝贝限购%s件，您已经购买%s件", detailsVo.restriction, num));
                            return;
                        }
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("goodsDetail", detailsVo);
                        toActivity(SubmitOrderFormActivity.class, bundle);
                    }
                }
            } else if (id == R.id.shop_base_but_right) {
                if (!TextUtils.isEmpty(detailsVo.shop_tel)) {
                    String phones[] = detailsVo.shop_tel.split(",");
                    ShopDialogStyle3 dialogStyle3 = null;
                    if (phones.length == 1) {
                        dialogStyle3 = new ShopDialogStyle3(GoodsDetailActivity.this, phones[0]);
                        dialogStyle3.show();
                    } else {
                        dialogStyle3 = new ShopDialogStyle3(GoodsDetailActivity.this, phones[0], phones[1]);
                        dialogStyle3.show();
                    }
                }
            } else if (id == R.id.btn_GoToMall) {
                toActivity(FirstActivity.class, null);
                GoodsDetailActivity.this.finish();
            } else {
            }
        }
    };

    /**
     * @author LK
     * @methods buyNow
     * @description 描述信息 立即购买
     * @date 2015-1-23 上午9:43:15 参数说明
     */
    private void buyNow() {
        if ("0".equals(detailsVo.available)) {
            int num = Integer.parseInt(detailsVo.restriction) - Integer.parseInt(detailsVo.available);
            showShortToast(String.format("宝贝限购%s件，您已经购买%s件", detailsVo.restriction, num));
            return;
        }
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("您的秒杀正在奋力拼抢中");
        try {
            dialog.show();
        } catch (Exception e) {
        }
        HttpUtils httpUtils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("por", "604");
        params.addQueryStringParameter("proIden", Constants.STOREFLAG);
        params.addQueryStringParameter("user_id", Constants.userCenterId);
        params.addQueryStringParameter("goods_id", detailsVo.id);
        params.addQueryStringParameter("order_time", String.valueOf(System.currentTimeMillis()));
        params.addQueryStringParameter("sign", SignUtil.generateSign(params));
        httpUtils.send(HttpMethod.POST, Constants.STORE_URL, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                super.onStart();
                LogUtils.i("getRequestUrl=" + this.getRequestUrl());
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                LogUtils.i("arg1========" + arg1);
                try {
                    dialog.dismiss();
                } catch (Exception e) {
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    dialog.dismiss();
                } catch (Exception e) {
                }
                String result = responseInfo.result;
                if (!TextUtils.isEmpty(result)) {
                    final BuyNowVo entity = JSON.parseObject(result, BuyNowVo.class);
                    if (null != entity) {
                        if (Constants.STORE_SUCCESS_CODE.equals(entity.getCode())) {
                            showShortToast(String.format("抢购成功，请在%d分钟内付款", entity.pay_time));
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("goodsDetail", detailsVo);
                                    bundle.putSerializable("msSign", entity.ms_sign);
                                    bundle.putString("mySign", entity.my_sign);
                                    toActivity(SubmitOrderFormActivity.class, bundle);
                                }
                            }, 2000);
                        } else if ("100".equals(entity.getCode())) {
                            showShortToast("被秒光了...\n去看看其他商品吧");
                        } else if ("103".equals(entity.getCode())) {
                            showShortToast("超出限购了\n你不能买这么多啊亲");
                        } else {
                            showShortToast(entity.getMessage());
                        }
                    }
                }
            }
        });
    }

    /***
     * @author LK
     * @methods concelConnection
     * @description 描述信息 取消收藏
     * @date 2015-1-25 下午1:23:11 参数说明
     */
    private void concelConnection() {
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("por", "507");
        params.addQueryStringParameter("user_id", Constants.userCenterId);
        params.addQueryStringParameter("obj_id", detailsVo.id);// 收藏商品ID
        params.addQueryStringParameter("proIden", Constants.STOREFLAG);
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpMethod.POST, Constants.STORE_URL, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                super.onStart();
                LogUtils.i("result=" + this.getRequestUrl());
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                if (!TextUtils.isEmpty(result)) {
                    BaseVo entity = JSON.parseObject(result, BaseVo.class);
                    if (null != entity) {
                        if (Constants.STORE_SUCCESS_CODE.equals(entity.getCode())) {
                            showShortToast(getString(R.string.cancel_connection));
                            btnCollection.setText("收藏");
                            detailsVo.is_collected = 0;
                        }
                    }
                }
            }
        });
    }

    /**
     * @author LK
     * @methods addCollection
     * @description 描述信息 收藏商品
     * @date 2015-1-20 上午10:22:00 参数说明
     */
    private void addCollection() {
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("por", "505");
        params.addQueryStringParameter("user_id", Constants.userCenterId);// 用户ID
        params.addQueryStringParameter("obj_id", detailsVo.id);// 收藏商品ID
        params.addQueryStringParameter("proIden", Constants.STOREFLAG);// 产品标识
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpMethod.POST, Constants.STORE_URL, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {
                super.onStart();
                LogUtils.i(">>>>>>>>>>>" + this.getRequestUrl());
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                LogUtils.i(">>>>>>>>>>>" + result);
                if (!TextUtils.isEmpty(result)) {
                    BaseVo entity = JSON.parseObject(result, BaseVo.class);
                    if (null != entity) {
                        if (Constants.STORE_SUCCESS_CODE.equals(entity.getCode()) || "9".equals(entity.getCode())) {
                            showShortToast(getString(R.string.collection_success));
                            btnCollection.setText("已收藏");
                            detailsVo.is_collected = 1;
                        }
                    }
                }
            }
        });
    }

    @Override
    public void setOrderData(GoodsDetailsVo detailsVo) {
        this.detailsVo = detailsVo;
        shopId = detailsVo.shop_id;
        goodsId = detailsVo.id;
        if (Constants.STORE_GOODSSOLDOUT_CODE.equals(detailsVo.getCode())) {
            goodsDown.setVisibility(View.VISIBLE);
            rlDetailsLayout.setVisibility(View.GONE);
            titleRightText.setVisibility(View.INVISIBLE);
            baseButRight.setClickable(false);
            return;
        }
        if (detailsVo.is_collected == 0) {
            btnCollection.setText("收藏");
        } else {
            btnCollection.setText("已收藏");
        }
        detailButtom.setVisibility(View.VISIBLE);
    }
}
